import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

/// 通用搜索框组件
/// 提供统一的搜索框样式，支持主题切换
class CommonSearchBar extends StatefulWidget {
  /// 提示文字
  final String hintText;

  /// 搜索回调
  final ValueChanged<String>? onSearch;

  /// 文字改变回调
  final ValueChanged<String>? onChanged;

  /// 提交回调
  final ValueChanged<String>? onSubmitted;

  /// 初始值
  final String? initialValue;

  /// 是否自动获取焦点
  final bool autofocus;

  /// 是否只读
  final bool readOnly;

  /// 是否显示清除按钮
  final bool showClearButton;

  /// 是否显示搜索按钮
  final bool showSearchButton;

  /// 前缀图标
  final Widget? prefixIcon;

  /// 后缀图标
  final Widget? suffixIcon;

  /// 背景颜色
  final Color? backgroundColor;

  /// 边框颜色
  final Color? borderColor;

  /// 圆角大小
  final double borderRadius;

  /// 高度
  final double? height;

  /// 外边距
  final EdgeInsetsGeometry? margin;

  /// 内边距
  final EdgeInsetsGeometry? padding;

  /// 控制器
  final TextEditingController? controller;

  const CommonSearchBar({
    super.key,
    this.hintText = '请输入搜索内容',
    this.onSearch,
    this.onChanged,
    this.onSubmitted,
    this.initialValue,
    this.autofocus = false,
    this.readOnly = false,
    this.showClearButton = true,
    this.showSearchButton = false,
    this.prefixIcon,
    this.suffixIcon,
    this.backgroundColor,
    this.borderColor,
    this.borderRadius = 25.0,
    this.height,
    this.margin,
    this.padding,
    this.controller,
  });

  @override
  State<CommonSearchBar> createState() => _CommonSearchBarState();
}

class _CommonSearchBarState extends State<CommonSearchBar> {
  late TextEditingController _controller;
  bool _showClear = false;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller ?? TextEditingController();
    if (widget.initialValue != null) {
      _controller.text = widget.initialValue!;
      _showClear = widget.initialValue!.isNotEmpty;
    }
    _controller.addListener(_onTextChanged);
  }

  @override
  void dispose() {
    if (widget.controller == null) {
      _controller.dispose();
    }
    super.dispose();
  }

  void _onTextChanged() {
    final text = _controller.text;
    setState(() {
      _showClear = text.isNotEmpty && widget.showClearButton;
    });
    widget.onChanged?.call(text);
  }

  void _onClear() {
    _controller.clear();
    widget.onChanged?.call('');
    widget.onSearch?.call('');
  }

  void _onSearch() {
    final text = _controller.text.trim();
    widget.onSearch?.call(text);
    widget.onSubmitted?.call(text);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: widget.height?.h ?? 44.h,
      margin: widget.margin ??
          EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      padding: widget.padding,
      decoration: BoxDecoration(
        color: widget.backgroundColor ?? context.theme.cardColor,
        borderRadius: BorderRadius.circular(widget.borderRadius.r),
        border: widget.borderColor != null
            ? Border.all(color: widget.borderColor!)
            : null,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4.r,
            offset: Offset(0, 2.h),
          ),
        ],
      ),
      child: Row(
        children: [
          // 前缀图标
          if (widget.prefixIcon != null) ...[
            Padding(
              padding: EdgeInsets.only(left: 12.w),
              child: widget.prefixIcon!,
            ),
          ] else ...[
            Padding(
              padding: EdgeInsets.only(left: 12.w),
              child: Icon(
                Icons.search,
                size: 20.w,
                color: context.theme.textTheme.bodySmall?.color,
              ),
            ),
          ],
          SizedBox(width: 8.w),
          // 输入框
          Expanded(
            child: TextField(
              controller: _controller,
              autofocus: widget.autofocus,
              readOnly: widget.readOnly,
              onSubmitted: widget.onSubmitted,
              decoration: InputDecoration(
                hintText: widget.hintText,
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                  color: context.theme.textTheme.bodySmall?.color,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.zero,
              ),
              style: TextStyle(
                fontSize: 14.sp,
                color: context.theme.textTheme.titleMedium?.color,
              ),
            ),
          ),
          // 清除按钮
          if (_showClear) ...[
            GestureDetector(
              onTap: _onClear,
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 8.w),
                child: Icon(
                  Icons.clear,
                  size: 18.w,
                  color: context.theme.textTheme.bodySmall?.color,
                ),
              ),
            ),
          ],
          // 后缀图标或搜索按钮
          if (widget.suffixIcon != null) ...[
            Padding(
              padding: EdgeInsets.only(right: 12.w),
              child: widget.suffixIcon!,
            ),
          ] else if (widget.showSearchButton) ...[
            GestureDetector(
              onTap: _onSearch,
              child: Container(
                margin: EdgeInsets.only(right: 4.w),
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                decoration: BoxDecoration(
                  color: context.theme.primaryColor,
                  borderRadius:
                      BorderRadius.circular((widget.borderRadius - 4).r),
                ),
                child: Text(
                  '搜索',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
          ] else ...[
            SizedBox(width: 12.w),
          ],
        ],
      ),
    );
  }
}

/// 筛选搜索框组件
/// 带有筛选功能的搜索框
class FilterSearchBar extends StatelessWidget {
  /// 提示文字
  final String hintText;

  /// 搜索回调
  final ValueChanged<String>? onSearch;

  /// 筛选回调
  final VoidCallback? onFilter;

  /// 是否有筛选条件
  final bool hasFilter;

  /// 控制器
  final TextEditingController? controller;

  /// 外边距
  final EdgeInsetsGeometry? margin;

  const FilterSearchBar({
    super.key,
    this.hintText = '请输入搜索内容',
    this.onSearch,
    this.onFilter,
    this.hasFilter = false,
    this.controller,
    this.margin,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: CommonSearchBar(
            hintText: hintText,
            onSearch: onSearch,
            controller: controller,
            margin: margin,
          ),
        ),
        SizedBox(width: 8.w),
        GestureDetector(
          onTap: onFilter,
          child: Container(
            width: 44.w,
            height: 44.w,
            margin: EdgeInsets.only(right: 16.w),
            decoration: BoxDecoration(
              color: hasFilter
                  ? context.theme.primaryColor
                  : context.theme.cardColor,
              borderRadius: BorderRadius.circular(12.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 4.r,
                  offset: Offset(0, 2.h),
                ),
              ],
            ),
            child: Icon(
              Icons.tune,
              size: 20.w,
              color: hasFilter
                  ? Colors.white
                  : context.theme.textTheme.bodyMedium?.color,
            ),
          ),
        ),
      ],
    );
  }
}

/// 分类搜索框组件
/// 带有分类选择的搜索框
class CategorySearchBar extends StatefulWidget {
  /// 提示文字
  final String hintText;

  /// 搜索回调
  final ValueChanged<String>? onSearch;

  /// 分类选择回调
  final ValueChanged<String>? onCategoryChanged;

  /// 分类列表
  final List<String> categories;

  /// 当前选中的分类
  final String? selectedCategory;

  /// 控制器
  final TextEditingController? controller;

  const CategorySearchBar({
    super.key,
    this.hintText = '请输入搜索内容',
    this.onSearch,
    this.onCategoryChanged,
    this.categories = const [],
    this.selectedCategory,
    this.controller,
  });

  @override
  State<CategorySearchBar> createState() => _CategorySearchBarState();
}

class _CategorySearchBarState extends State<CategorySearchBar> {
  String? _selectedCategory;

  @override
  void initState() {
    super.initState();
    _selectedCategory = widget.selectedCategory;
  }

  void _showCategorySelector() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: EdgeInsets.all(16.w),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '选择分类',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: context.theme.textTheme.titleMedium?.color,
              ),
            ),
            SizedBox(height: 16.h),
            ...widget.categories.map((category) => ListTile(
                  title: Text(category),
                  trailing: _selectedCategory == category
                      ? Icon(
                          Icons.check,
                          color: context.theme.primaryColor,
                        )
                      : null,
                  onTap: () {
                    setState(() {
                      _selectedCategory = category;
                    });
                    widget.onCategoryChanged?.call(category);
                    Navigator.pop(context);
                  },
                )),
            ListTile(
              title: const Text('全部'),
              trailing: _selectedCategory == null
                  ? Icon(
                      Icons.check,
                      color: context.theme.primaryColor,
                    )
                  : null,
              onTap: () {
                setState(() {
                  _selectedCategory = null;
                });
                widget.onCategoryChanged?.call('');
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        CommonSearchBar(
          hintText: widget.hintText,
          onSearch: widget.onSearch,
          controller: widget.controller,
        ),
        if (widget.categories.isNotEmpty) ...[
          SizedBox(height: 8.h),
          Container(
            height: 40.h,
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            child: ListView(
              scrollDirection: Axis.horizontal,
              children: [
                _buildCategoryChip('全部', _selectedCategory == null),
                ...widget.categories.map((category) => _buildCategoryChip(
                    category, _selectedCategory == category)),
              ],
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildCategoryChip(String category, bool isSelected) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedCategory = category == '全部' ? null : category;
        });
        widget.onCategoryChanged?.call(category == '全部' ? '' : category);
      },
      child: Container(
        margin: EdgeInsets.only(right: 8.w),
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        decoration: BoxDecoration(
          color:
              isSelected ? context.theme.primaryColor : context.theme.cardColor,
          borderRadius: BorderRadius.circular(20.r),
          border: Border.all(
            color: isSelected
                ? context.theme.primaryColor
                : context.theme.dividerColor,
          ),
        ),
        child: Text(
          category,
          style: TextStyle(
            fontSize: 14.sp,
            color: isSelected
                ? Colors.white
                : context.theme.textTheme.bodyMedium?.color,
            fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
          ),
        ),
      ),
    );
  }
}
